const Router = require('koa-router')
const Fav = require('../model/fav.js')
const Order = require('../model/order.js')
const User = require('../model/users.js')
const jwt = require('jsonwebtoken')
const UserInfo = new Router()

// 查询收藏列表
UserInfo.get('/userInfo', async ctx => {
    try {
        // 请求头中的token 解析后带有‘Bearer ’和空格，因此需要按空格截取
        let getToken = ctx.request.header.authorization.split(' ')[1]
        // 将截取后的字符串再通过decode反解出openid
        let openid = jwt.decode(getToken).info
        let res = await User.find({openId: openid})
        if (!res) {
            ctx.body = {
                code: 0,
                data: "",
                msg:'非法用户'
            }
        } else {
            let orderRes = await Order.find({ userOpenid: openid })
            let favRes = await Fav.find({ userOpenid: openid })
            ctx.body = {
                code: 2,
                data: {
                    orderCount:orderRes.length,
                    favCount:favRes.length
                }
            }
        }

    } catch (error) {
        //TODO handle the exception
        console.log(error)
    }
})
module.exports = UserInfo